<template>
  <!--后台 添加音乐组件 -->
  <el-dialog
    :title="title"
    :visible="visible"
    :before-close="closeHandler"
    center
    custom-class="toast-class"
    :width="screenWidth < 768 ? '80%' : '40%'"
  >
    <!-- 主要内容 -->
    <div class="upload-music">
      <div class="form-item">
        <label for="">音乐名称</label>
        <input
          v-model="musicObj.name"
          class="custom_ipt"
          placeholder="请输入音乐名称"
        />
      </div>
      <div class="form-item">
        <label for="">演唱者</label>
        <input
          v-model="musicObj.author"
          class="custom_ipt"
          placeholder="请输入演唱者名称"
        />
      </div>
      <div class="form-item">
        <label for="">音乐地址</label>
        <input
          v-model="musicObj.src"
          class="custom_ipt"
          placeholder="支持音乐URL"
        />
        <label for="uploadMusic" class="uploadMusic">上传</label>
        <input
          hidden
          type="file"
          name="musicFile"
          id="uploadMusic"
          ref="uploadMusic"
          @input="uploadMusic"
          accept="audio/mpeg"
        />
      </div>
      <div class="form-item">
        <audio class="aud" ref="aud" :src="musicObj.src" controls></audio>
      </div>
      <div class="form-item btn clearfix">
        <button @click="addMusicHandler">确认添加</button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { nanoid } from "nanoid";
import { mapMutations, mapState } from "vuex";
export default {
  name: "FormToast",

  /* 标题以及是否展示 */
  props: ["title", "visible"],
  data() {
    return {
      /* 填写信息 对象 */
      musicObj: {
        name: "",
        author: "",
        src: "",
      },
    };
  },
  computed: {
    /* 获取视口宽度 */
    ...mapState("music", ["screenWidth"]),
  },
  methods: {
    /* 后台添加音乐的方法 */
    ...mapMutations("music", ["BACKADDMUSIC"]),
    /* 检测字段完整性 */
    validateData(musicObj) {
      const validate = [];
      for (const key in musicObj) {
        if (Object.hasOwnProperty.call(musicObj, key)) {
          if (!musicObj[key].toString()) {
            validate.push(key);
          }
        }
      }
      return validate;
    },
    /* 判断音频是否合法 */
    audioIsLegal() {
      const aud = this.$refs["aud"];
      return aud["duration"] ? true : false;
    },
    /* 添加音乐 */
    addMusicHandler() {
      const musicObj = Object.assign({}, this.musicObj, {
        isPlay: false,
        islike: false,
        setout: true,
        state: 0,
        musicId: nanoid(),
      });
      /* 校验数据 */
      const validate = this.validateData(musicObj);
      if (validate.length) {
        return this.$message({
          message: `${validate.toString()}等字段未填写`,
          type: "error",
        });
      }
      /* 校验音频文件 */
      if (!this.audioIsLegal()) {
        return this.$message({
          message: "音频文件不合法",
          type: "error",
        });
      }
      /* 提交后台 */
      this.BACKADDMUSIC(musicObj);

      /* 异步一下 */
      this.$nextTick(function () {
        /* 提交后清空数据 */
        for (const key in this.musicObj) {
          if (Object.hasOwnProperty.call(musicObj, key)) {
            this.$set(this.musicObj, key, "");
          }
        }
        /* 关闭弹出层 */
        this.closeHandler();
        this.$message({ message: "音乐添加成功", type: "success" });
      });
    },
    /* 关闭弹出层 */
    closeHandler() {
      this.$emit("close", false);
    },
    /* 上传音乐 */
    uploadMusic() {
      let file = this.$refs["uploadMusic"]["files"][0];
      const blob = new Blob([file], { type: "audio/mpeg" }); // 指定转换成blob的类型
      this.musicObj.src = URL.createObjectURL(blob); //转为本地临时链接
      // const reader = new FileReader(); // 3 新建 FileReader 对象,用于操作文件
      // reader.onload = (ev) => {
      //   const base64Url = ev.target.result; // 5 base64内容
      //   // this.musicObj.src = base64Url;
      // };
      // reader.readAsDataURL(blob); // 4 将文件转换成指定类型的数据
    },
  },
};
</script>

<style lang="less" scoped>
.clearfix:after {
  content: ""; /*设置内容为空*/
  clear: both; /*清除浮动*/
  display: block; /*将文本转为块级元素*/
  height: 0; /*高度为0*/
  visibility: hidden; /*将元素隐藏*/
}
.clearfix {
  zoom: 1; /*为了兼容IE*/
}

.upload-music {
  .form-item {
    margin-bottom: 0.3rem;
    &.btn {
      button {
        padding: 0.2rem 0.5rem;
        cursor: pointer;
        background-color: #67c23a;
        border: 0;
        outline: none;
        color: #333;
        border-radius: 0.05rem;
        font-size: 0.2rem;
      }
    }
    label {
      color: #aaa;
      display: inline-block;
      width: 1.5rem;
      &.uploadMusic {
        margin-left: 0.3rem;
        width: auto;
        cursor: pointer;
      }
    }
    input[type="file"] {
      color: #aaa;
    }
  }
}

.el-dialog__header {
  color: #ffcff1 !important;
  .el-dialog__title {
    color: inherit;
  }
}

@media screen and (max-height: 768px) {
  .aud {
    display: none !important;
  }
  .form-item {
    button {
      float: right;
    }
  }
}
</style>